import random
import string
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, AsyncEngine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
import os
from basic import logger

# 获取数据库文件路径
DB_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data.db")
# SQLite的异步URL
SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_FILE}"

# 创建异步引擎
engine = create_async_engine(
    SQLALCHEMY_DATABASE_URL,
    poolclass=NullPool,  # SQLite不需要连接池
    connect_args={"check_same_thread": False}  # SQLite需要这个参数来支持多线程
)

# 创建异步会话工厂
AsyncSessionLocal = sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False
)

async def get_db():
    """
    获取数据库会话的依赖函数
    
    Yields:
        AsyncSession: 数据库会话
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()

async def init_db():
    """
    初始化数据库，创建所有表
    
    Returns:
        None
    """
    from .models import Base
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
        print("Base.metadata.create_all")
    logger.info("FAST_API init_db")

def generate_random_string(length: int) -> str:
    # 62个字符，包含26个大写字母、26个小写字母和10个数字
    characters = string.ascii_uppercase + string.ascii_lowercase + string.digits
    return ''.join(random.choice(characters) for _ in range(length))